package com.demo.controller;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.demo.common.config.DemoConfig;
import com.demo.common.constant.DictKeys;
import com.demo.common.model.AuthUser;
import com.demo.utils.Result;
import com.demo.utils.StrUtil;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

public class BaseController<M extends Model<M>> extends Controller{
	private static Logger logger = Logger.getLogger(BaseController.class);
	protected Class<M> clazz;
	
	@SuppressWarnings("unchecked")
	public BaseController(){
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		this.clazz = (Class<M>) pt.getActualTypeArguments()[0];
		logger.debug("clazz="+clazz.getName());
	}
	/**
	 * 方法成功执行
	 * @param obj   一个对象
	 */
	public void success(Object obj){
		renderJson(new Result(DictKeys.SUCCESS_CODE,DictKeys.SUCCESS_MSG,obj));
	}
	/**
	 * 方法执行失败
	 * @param msg
	 */
	public void error(String msg){
		renderJson(new Result(DictKeys.FAIL_CODE,DictKeys.FAIL_MSG,msg));
		
	}
	
	protected AuthUser getCurrentUser(){
		return (AuthUser) getSession().getAttribute(DictKeys.SESSION_ADMIN_USER);
	}
	
	/**
	 * 获取map封装的注册  拆装成map
	 * @return
	 */
	protected Map<String, Object> getQueryParam(){
		Map<String, Object> queryParam = new HashMap<String, Object>();
		Enumeration<String> paramNames = getParaNames();
		while (paramNames.hasMoreElements()) {
			String name = paramNames.nextElement();
			int index = name.indexOf("[");
			if(index>0){ 
				  String tmp = name.substring(index+1, name.length()-1);
				  queryParam.put(tmp, getPara(name));
			  }
		}
		return queryParam;
		
	}
	/**

	 * 通用分页查找

	 */
	public void findByPage(Map<String, Object> params) {
		List<Object> paramsList = new ArrayList<Object>();
		String select = "select *";
		StringBuilder sqlExceptSelect = new StringBuilder("from t_" + clazz.getSimpleName() + " where 1 = 1 ") ;
		if(params!=null&&params.size()>0){
			 for(String key:params.keySet()){
				 sqlExceptSelect.append(" and o.").append(key).append("= ?");
				 paramsList.add(params.get(key).toString());  
			 }
			
		}
		sqlExceptSelect.append(" order by createDate desc ");				
		Page<M> pager = getModel(clazz).paginate(getParaToInt("page", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect.toString());
		renderJson(pager);
		//setAttr("pager", pager);
	}
	/**

	 * 通用查找全部

	 */
	public void getAll() {
		renderJson(Db.find("select * from t_" + clazz.getSimpleName() + " where status != '0' order by id asc;"));
	}
	
	/**

	 * 根据表名、属性名称、属性值判断在数据库中是否唯一(若新修改的值与原来值相等则直接返回true).

	 * 

	 * @param tableName

	 *            表名

	 * @param propertyName

	 *            属性名称

	 * @param value

	 *            属性值

	 * @return boolean

	 */
	public boolean isUnique(String tableName,String propertyName, String value) {		
		if (StrUtil.notBlank(tableName) && StrUtil.notBlank(propertyName) && StrUtil.notBlank(value)) {
			String sql = "select * from " + tableName + " where " + propertyName + " = ? ";
			return Db.findFirst(sql,value) == null;
		}else{
			return false;
		}		
	}
	
}
